from usr.aliyun_operation import Aliyun
from usr.uart import Uart
import utime
from queue import Queue
import _thread
import ujson
import sys
import log

from usr.OTA_4G_Freescale_communication import add_crc16_and_uart_send

# 设置日志输出级别
log.basicConfig(level=log.DEBUG)
uart_log = log.getLogger("【main】")


# 登录阿里云设备证书
PRODUCT_KEY = 'h1cppPgQzDW'
DEVICE_NAME = 'OTA_CAN_Tool'
DEVICE_SECRET = '6ad6a307c94c81789465c2414af4a83d'


# 创建阿里云客户端
def create_aliyun_client(rev_q):
    uart_log.info('begin to connect Aliyun ...') 
    aliyun = Aliyun(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, rev_q) # 会block程序
    if aliyun.get_aliyun_isConnected() is True:
        uart_log.info('connected Aliyun server success.') 
        return aliyun
    
    return None    
   
# 阿里云相关操作线程
def aliyun_operation_thread(aliyun_obj, rev_q, send_q):
    time_start = utime.time()
    
    while True:
        if aliyun_obj.get_aliyun_isConnected() is True:
            if not send_q.empty():
                dict_data = send_q.get()
                uart_log.debug('aliyun_operation_thread-->send_data_queue: {}'.format(dict_data))

                #dict_data = ujson.loads(data)
                aliyun_obj.publish_topic(dict_data)
                
            #发送4g模块连接阿里云状态，便于在客户端显示
            if (utime.time() - time_start) > 5:  # 每隔5s,发送一次状态信息
                status_dict_data = {"OTA_CAN_ConnectAliyunState": "OTA-CAN has connected Aliyun!"}
                aliyun_obj.publish_topic(status_dict_data)
                time_start = utime.time()
                
        utime.sleep(0.3)
          
        pass

#Uart操作线程
def uart_thread(uart_obj, rev_q, send_q):
    
    while True:
        if not rev_q.empty():
            str_data = rev_q.get()
            uart_log.debug('uart_thread-->receive_data_queue: {}'.format(str_data))
            
            # 对要发送的数据添加crc16校验和，并发送
            add_crc16_and_uart_send(uart_obj, str_data)
        
        utime.sleep(0.3)
        pass



if __name__ == '__main__': 
    receive_queue = Queue()
    send_queue = Queue()
    
    #创建阿里云客户端
    aliyun = create_aliyun_client(receive_queue)
    if not aliyun:
        uart_log.error("create aliyun client failed, exit program")
        sys.exit(-1)
    
    # 实例化一个串口
    uart = Uart(send_queue)
    if not uart:
        uart_log.error("create uart object failed, exit program")
        sys.exit(-2)
        
    # 等待5s稳定后在继续进行
    utime.sleep(5)
    
    # 清空队列
    while not receive_queue.empty():
        receive_queue.get()
        print("empty receive_queue")
    while not send_queue.empty():
        send_queue.get()
        print("empty send_queue")
    
    # 创建线程
    thread_uart = _thread.start_new_thread(uart_thread, (uart, receive_queue, send_queue))
    thread_aliyun = _thread.start_new_thread(aliyun_operation_thread, (aliyun, receive_queue, send_queue))
    
    
    
    

    